<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浅拷贝和深拷贝</title>
</head>
<body>
    <!-- 
        1.浅拷贝方法
            Object.assign()
            _.clone
            展开运算符
            Array.concat()
            Array.splice()
        2.深拷贝方法
            Json.parse(Json.stringfy(obj))

     -->
    <script>
        let _ = require('lodash');

        let obj1 = {
            a: 1,
            b: {
                age: 23,
                name: {
                    fn: 'hu'
                }
            },
            c: [1, 2, 3]
        }
        let obj2 = _.cloneDeep(obj1);
        console.log(obj2)
        

        function shallowClone(obj) {
            let cloneObj = new Object();

            for(let item in obj) {
                cloneObj[item] = obj[item];
            }
            return cloneObj;
        }

        // 深拷贝
        function deepClone(obj) {
            if(obj === null) {
                return {};
            }
            if(obj instanceof Date){
                return new Date(obj);
            }
            if(obj instanceof RegExp) {
                return new RegExp(obj);
            }
            if(typeof obj !== "object") {
                return obj;
            }
            let cloneObj = {};
            for(let key in obj) {
                if(obj.hasOwnProperty(key)) {
                    cloneObj[key] = deepClone(obj[key]);
                }
            }
            return cloneObj;
        }

        let person = {
            name: 'huli',
            age: 23,
            habit: [1, 2, 3],
            hobby: {
                sport: 'football',
                music: 'classic'
            }
        }

        let person2 = shallowClone(person); //  浅复制 不改原始值 引用值改变
        let person3 = person; // 赋值 原始值 引用值都随之改变
        let personD = deepClone(person);
		
		function deepCopy(obj, map = new Map()) {
		  if (typeof obj === 'object') {
		     let res = Array.isArray(obj) ? [] : {};
			 if(map.get(obj)){
				return map.get(obj);
			 }
			 map.set(obj,res);
		     for(var i in obj){
				res[i] = deepCopy(obj[i],map);
			 }
			 return map.get(obj);
		  }else{
			return obj;
		  }
		};
		var A={a:1};
		A.A=A;
		
		var B = deepCopy(A);
		console.log(deepClone(A))
		console.log(B);//{a: 1, A: {a: 1, A: {…}}
    </script>
</body>
</html>